<?php

/**
 * Class for viewing a form in HTML.
 *
 * @author Ian Clarence <ian.clarence@gmail.com>
 */
class ViewHtmlForm extends ViewHtmlElement {

    /**
     * The constructor.
     *
     * @param array $fields
     */
    public function __construct(array $fields = array()) {

        $fields["tag"] = "form";
        $fields["file_uploads"] = isset($fields["file_uploads"]) ? $fields["file_uploads"] : FALSE;
        $fields["enctype"] = $fields["file_uploads"] ?  "multipart/form-data" : "application/x-www-form-urlencoded";
        $fields["method"] = isset($fields["method"]) ? $fields["method"] : "post";

        parent::__construct($fields);

        if (isset($this->fields["name"])) {
            $this->setAttribute("name", $this->getName());
        }

        if (isset($this->fields["action"])) {
            $this->setAttribute("action", $this->getAction());
        }
        else {
            $this->setAttribute("action", $_SERVER['PHP_SELF']);
        }

        $this->setAttribute("method", $this->getMethod());

        $this->setAttribute("enctype", $this->getEnctype());
        
    }
    
    /**
     * Returns a ViewHtmlForm object.
     * 
     * @param int $id
     * @param string $name
     * @param string $method
     * @param string $action
     * @param bool $fileUploads
     * @param array $params
     * @return \self 
     */
    public static function htmlFormInit(
        $id = NULL, 
        $name = NULL, 
        $method = 'post', 
        $action = NULL, 
        $fileUploads = FALSE,
        $params = array()
    ) {
        $output = new self(
            array(
                'id' => $id,
                'name' => $name,
                'method' => $method,
                'action' => $action == NULL ? $_SERVER['PHP_SELF'] : $action,
                'file_uploads' => $fileUploads
            )
        );
        $action = ViewInputText::inputTextInit('action', 'action', 'hidden', $name);
        $sessionId = ViewInputText::inputTextInit('session_id', 'session_id', 'hidden', $params['session_id']);
        $output->addInnerHtml($action);
        $output->addInnerHtml($sessionId);
        return $output;
    }

    /**
     * Returns an HTML object with inner HTML already added, and an optional attribute.
     *
     * @param string $tag
     * @param mixed $content
     * @param string $attributeName
     * @param string $attributeValue
     * @return ViewHtmlElement
     */
    public static function init($tag, $content, $attributeName = NULL, $attributeValue = NULL) {
        return parent::elementInit($tag, $content, $attributeName, $attributeValue);
    }
    
    /**
     * Adding the Submit button to the form.
     * 
     * @param bool $isButton 
     */
    public function addButton($isButton = FALSE) {
        $button = $isButton ? new ViewButton : new ViewSubmit;
        $this->addInnerHtml($button);
    }

}